package org.springblade.common.security.util;

import lombok.experimental.UtilityClass;
import org.springblade.common.constant.SecurityConstants;
import org.springblade.common.security.service.CsjUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.user.entity.UserInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

@UtilityClass
public class UserDetailUtil {
	public CsjUser getUserDetails(R<UserInfo> result) {
		if(Func.isEmpty(result) || Func.isEmpty(result.getData())){
			throw new UsernameNotFoundException("用户不存在");
		}

		UserInfo info = result.getData();
		Set<String> dbAuthsSet = new HashSet<>();
		if (Func.isNotEmpty(info.getRoles())) {
			// 获取角色
			info.getRoles().forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
			// 获取资源
			dbAuthsSet.addAll(info.getPermissions());

		}
		Collection<? extends GrantedAuthority> authorities
			= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		// 构造security用户
		return new CsjUser(info,SecurityConstants.BCRYPT + info.getUser().getPassword() ,authorities);
	}
}
